//
//  JKBaseViewController.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/6/29.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit

class JKBaseViewController: UIViewController {
    
    
    var visitorInfoDictionary: [String: String]?
    
    
    var tableView: UITableView?
    
    // 刷新控件
    var refreshControl: CZRefreshControl?
    
    // 上拉刷新标记
    var isPullup = false
    
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    
    lazy var navItem = UINavigationItem()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
//        loadData()
        JKNetworkManager.shared.userLogon ? loadData() : ()
    
        
        // 注册通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(loginSuccess),
            name: NSNotification.Name(rawValue: JKUserLoginSuccessedNotification),
            object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    
    // MARK - 加载数据
    func loadData() {
        // 默认关闭刷新控件
        refreshControl?.endRefreshing()
    }

    // 添加 navItem 的 名字
   override var title: String? {
        didSet {
            navItem.title = title
        }
    }

}


// MARK - 实现数据源方法和代理方法 
extension JKBaseViewController: UITableViewDataSource, UITableViewDelegate {
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
    
    // 在显示最后一行的时候, 做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let row = indexPath.row
        
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0 {
           return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row == (count - 1) && !isPullup {
            
            print("上拉刷新")
            isPullup = true
            
            loadData()
        }
    }

}

extension JKBaseViewController {

    private func setupUI() {
    
        view.backgroundColor = UIColor.cz_random()
    
        automaticallyAdjustsScrollViewInsets = false
        
        setupNavigationBar()
        
//        userLogon ? setupTableView() : setupVisitorView()
        JKNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView()
    }
    

    // 设置访客视图
    
    private func setupVisitorView() {
    

        let visitorView = JKVisitorView(frame: view.bounds)
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        print("访客视图 \(visitorView)")
        visitorView.visitorInfo = visitorInfoDictionary
        
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        
    }
    
    
}

// MARK - 访客视图监听方法 

extension JKBaseViewController {

    @objc private func loginSuccess(n: Notification) {
    
        print("登录成功 \(n)")
        
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        // 将view = nil 相当于 loadView方法
        view = nil
        
        NotificationCenter.default.removeObserver(self)
    }
    
    
    @objc private func login() {
       
        // 发送通知
        NotificationCenter.default.post(name: Notification.Name(rawValue: JKUserShouldLoginNotification), object: nil)
    }

    @objc private func register() {
       
        print("用户注册")
    }

}




 // MARK - 设置界面
extension JKBaseViewController {
        
        // 添加导航条
    private func setupNavigationBar() {
            
        view.addSubview(navigationBar)
        
        navigationBar.items = [navItem]
            
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
            
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray()]
    
        navigationBar.tintColor = UIColor.orange()

    }

        
        
     func setupTableView() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        tableView?.dataSource = self
        tableView?.delegate = self
        
        // 表格内容的偏移 --> 跟缩进的效果一样
//        tableView?.contentInset = UIEdgeInsetsMake(navigationBar.bounds.height,
//                                                   0,
//                                                   tabBarController?.tabBar.bounds.height ?? 49,
//                                                   0)
        // 表格内容缩进
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height,
                                               left: 0,
                                               bottom: tabBarController?.tabBar.bounds.height ?? 49,
                                               right: 0)
        
        // 修改指示器的缩进 - 强心解包是为了拿到一个必有的 inset
        tableView?.scrollIndicatorInsets = (tableView?.contentInset)!
        
        refreshControl = CZRefreshControl()
        
        tableView?.addSubview(refreshControl!)
        
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    

}
